﻿using ProjectTemplate.API.Middlewares;
using ProjectTemplate.API.Models;

using Tszy.Unlimited.AspNetCore;
using Tszy.Unlimited.Base.Extensions;
using Tszy.Unlimited.Data.FreeSQL;

namespace ProjectTemplate.API;

public static class Startup
{
    public static void Configure(this WebApplicationBuilder builder)
    {
        builder.RegisterTszyComponent().RegisterSwagger("Project API 文档").RegisterCors().Configure();
    }

    public static void UseApp(this WebApplication app)
    {
        if (!string.IsNullOrWhiteSpace(SettingData.Instance.Project.Rule))
            app.Urls.Add(SettingData.Instance.Project.Rule);

        app.UseTszyComponent().UseSwagger().UseCors();
        app.UseMiddleware<MainRequestCoreFilter>();
    }

    public static void Configure(this TszyAspNetCoreConfiguration aspNetCoreConfiguration)
    {
        aspNetCoreConfiguration.Services.ConfigureCore(aspNetCoreConfiguration.Configuration);
        aspNetCoreConfiguration.Services.ConfigureServices(aspNetCoreConfiguration.Configuration);
    }
}

public static class ConfigureExtensions
{
    public static void ConfigureServices(this IServiceCollection services, IConfiguration configuration)
    {
        services.RegisterConfigs(configuration);
        services.RegisterDatabase();
    }

    /// <summary>
    /// 配置设置信息。
    /// </summary>
    /// <param name="services"></param>
    /// <param name="configuration"></param>
    public static IServiceCollection RegisterConfigs(this IServiceCollection services, IConfiguration configuration)
    {
        //初始化配置信息。
        SettingData.Initialize(configuration.Get<SettingData>());

        return services;
    }

    public static IServiceCollection RegisterDatabase(this IServiceCollection services)
    {
        if (SettingData.Instance?.Database == null)
            return services;

        //初始化 Linq 数据组件。
        var connectionString = SettingData.Instance.Database.DbConnection ?? string.Empty;

        if (string.IsNullOrWhiteSpace(connectionString))
            return services;

        if (!string.IsNullOrWhiteSpace(SettingData.Instance.Database.DbKey))
        {
            connectionString = connectionString.AES32Decrypt(SettingData.Instance.Database.DbKey);
        }

        services.RegisterFreeSQLDotMySQL(connectionString);

        return services;
    }
}